Page({

  /**
   * 页面的初始数据
   */
  data: {
      address: "XX省XX市XX区XX街道XX号XX室",
      cartEffectList: [],
      // 生效商品
      example: [
          {
              store: "索尼旗舰店",
              checked: false,
              merchandiseChecked: false,
              merchandises: [
                  {
                      id: "1",
                      imgUrl: "/pages/logs/image/索尼耳机.jpg",
                      name: "Sony/索尼 WH-CH720N 舒适高效 头戴式降噪耳机 长久佩戴",
                      price: 899,
                      amount: 1,
                      status: 0,
                      x: 0,
                      checked: false,
                  },
                ]
          },
          {
            store: "九达电脑",
            checked: false,
            merchandiseChecked: false,
            merchandises: [
                {
                    id: "1",
                    imgUrl: "/pages/logs/image/4090.jpg",
                    name: "全新原盒RTX4090显卡ROG黑猛禽华硕TUF白猛禽24G OC显卡魔龙魔鹰",
                    price: 14187,
                    amount: 1,
                    status: 0,
                    x: 0,
                    checked: false,
                },
              ],
          },
          {
            store: "三只松鼠旗舰店",
            checked: false,
            merchandiseChecked: false,
            merchandises: [
                {
                    id: "1",
                    imgUrl: "/pages/logs/image/三只松鼠.jpg",
                    name: "【三只松鼠巨型零食大礼包30袋】坚果肉脯中秋节礼物解馋小吃零食",
                    price: 49,
                    amount: 1,
                    status: 0,
                    x: 0,
                    checked: false,
                },
              ],
          }
      ],
      startX: 0,
      moveStore: '',
      delBtnW: 128,
      isLeft: 0,
      total: 0,
      totalCount: 0,
      checkedAll: false,
      billLoading: false,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
      this.getCartList();
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 获取用户购物车
   */
  getCartList() {
      let cartEffectList = this.data.example;
      wx.setStorageSync('cartEffectList', cartEffectList);
      this.setData({
          cartEffectList: cartEffectList,
      });
  },

  /**
   * 店铺全选
   * @param {*} e 
   */
  checkStoreAll(e) {
      let storeName = e.currentTarget.dataset.store;
      let cartEffectList = this.data.cartEffectList;
      let updatedCart = cartEffectList.map(store => {
          if (store.store === storeName) {
              // 切换商店的已勾选标记
              store.checked = !store.checked;
              // 重置商店的商品已勾选标记
              store.merchandiseChecked = false;
              store.merchandises = store.merchandises.map(merch => {
                  // 根据商店的已检查标记更新商品的已选择标记
                  merch.checked = store.checked;
                  return merch;
              });
          }
          return store;
      });
      this.setData({
          cartEffectList: updatedCart
      });
      this.grand();
  },

  /**
   * 单个选择
   * @param {*} e 
   */
  checkSingle(e) {
      let storeName = e.currentTarget.dataset.store;
      let merchandiseData = e.currentTarget.dataset.merchandise;
      let cartEffectList = this.data.cartEffectList;
  
      let updatedCart = cartEffectList.map(store => {
          if (store.store === storeName) {
              store.merchandises = store.merchandises.map(merch => {
                  if (merch.id === merchandiseData.id) {
                      // 更改商品的选择状态
                      merch.checked = !merch.checked;
                      // 更改店铺的选中状态
                      store.merchandiseChecked = merch.checked;
                  }
                  return merch;
              });
          }
          return store;
      });
  
      this.setData({
          cartEffectList: updatedCart
      });
      this.grand();
  },

  /**
   * 减少数量，下限为1
   * @param {*} e 
   */
  minusAmount(e) {
      let storeName = e.currentTarget.dataset.store;
      let id = e.currentTarget.dataset.id;
      let cartEffectList = this.data.cartEffectList;
      let updatedCart = cartEffectList.map(store => {
          if (store.store === storeName) {
              // 更新商店的已选择商品标记
              store.merchandiseChecked = true;
              store.merchandises = store.merchandises.map(merch => {
                  if (merch.id === id) {
                      // 更新商品的选择状态
                      merch.checked = true;
                      if (merch.amount > 1) {
                          merch.amount--;
                      } else {
                          wx.showModal({
                              content: '宝贝数量不能再减少了',
                              showCancel: false,
                          });
                      }
                  }
                  return merch;
              });
          }
          return store;
      });
  
      this.setData({
          cartEffectList: updatedCart
      });
      this.grand();
  },

  /**
   * 增加数量，上限为99
   * @param {*} e 
   */
  plusAmount(e) {
      let storeName = e.currentTarget.dataset.store;
      let id = e.currentTarget.dataset.id;
      let cartEffectList = this.data.cartEffectList;
      let updatedCart = cartEffectList.map(store => {
          if (store.store === storeName) {
              // 更新店铺的选中状态
              store.merchandiseChecked = true;
              store.merchandises = store.merchandises.map(merch => {
                  if (merch.id === id) {
                      // 更新商品的选择状态
                      merch.checked = true; 
                      if (merch.amount < 99) {
                          merch.amount++;
                      } else {
                          wx.showModal({
                              content: '宝贝数量不能再增加了',
                              showCancel: false,
                          });
                      }
                  }
                  return merch;
              });
          }
          return store;
      });
      this.setData({
          cartEffectList: updatedCart
      });
      this.grand();
  },

  /**
   * 删除商品
   * @param {*} e 
   */
  deleteMerchandise(e) {
      let storeName = e.currentTarget.dataset.store;
      let id = e.currentTarget.dataset.id;
      let cartEffectList = this.data.cartEffectList;
      let cartLapseList = this.data.cartLapseList;
      // 遍历每个商店
      let updatedEffectCart = cartEffectList.map(store => {
          if (store.store === storeName) {
              // 如果是目标商店，过滤掉指定ID的商品
              store.merchandises = store.merchandises.filter(merch => merch.id !== id);
          }
          return store;
      });
      cartLapseList = cartLapseList.filter(item => item.id !== id);
      this.setData({
          cartEffectList: updatedEffectCart,
          cartLapseList: cartLapseList
      });
  },

  /**
   * 全选
   */
  checkAll() {
      let cartEffectList = this.data.cartEffectList;
      let checkedAll = this.data.checkedAll;
      // 使用map方法更新每个商店和商品的选中状态
      let updatedCart = cartEffectList.map(store => {
          return {
              ...store,
              checked: !checkedAll,
              merchandiseChecked: !checkedAll,
              merchandises: store.merchandises.map(merch => ({
                  ...merch,
                  checked: !checkedAll
              }))
          };
      });
      this.setData({
          cartEffectList: updatedCart,
          checkedAll: !checkedAll,
      });
      this.grand();
  },

  /**
   * 合计
   */
  grand() {
      let cartEffectList = this.data.cartEffectList;
      // 初始化总价和总数量
      let total = 0;
      let totalCount = 0;
      cartEffectList.forEach(store => {
          store.merchandises.forEach(merch => {
              if (merch.checked) {
                  total += merch.amount * merch.price;
                  totalCount += merch.amount;
              }
          });
      });
      this.setData({
          total: total,
          totalCount: totalCount,
      });
  },

  /**
   * 结算
   */
  settleBill() {
      this.setData({
          showLoading: true,
      });
      // 进行深拷贝
      let cartEffectList = JSON.parse(JSON.stringify(this.data.cartEffectList));

      // 筛选出未选中的商店或没有选中商品的商店
      let filteredStores = cartEffectList.filter(store => {
          if (store.checked) {
              // 如果商店被选中，保留它
              return true; 
          }
          // 从商店中筛选出未选中的商品
          store.merchandises = store.merchandises.filter(merch => merch.checked);
          // 如果筛选后，商店有选中的商品，保留该商店
          return store.merchandises.length > 0;
      });

      wx.navigateTo({
          url: `/pages/index/settle-bill/settle-bill?chosenList=${JSON.stringify(filteredStores)}`,
          complete: () => {
              this.setData({
                  showLoading: false,
              });
          }
      });
  },

  /**
   * 开始滑动
   * @param {*} e 
   */
  touchStart (e) {
      let index = e.currentTarget.dataset.id;
      let store = e.currentTarget.dataset.store;
      let cartEffectList = this.data.cartEffectList;
      let cartLapseList = this.data.cartLapseList;
      // 复位，这样子就能保证一次显示一个删除按钮
      for (let i in cartEffectList) {
          for (let j in cartEffectList[i].merchandises) {
              cartEffectList[i].merchandises[j].x = 0
          }
      }
      for (let i in cartLapseList) {
          cartLapseList[i].x = 0;
      }
      // 判断是否为多触点
      if (e.touches.length == 1) {
          // 记录开始触摸的位置
          this.setData({
              startX: e.touches[0].clientX,
              cartEffectList: cartEffectList,
              cartLapseList: cartLapseList
          });
      }
  },
  /**
   * 开始移动
   * @param {*} e 
   */
  touchMove (e) {
      let id = e.currentTarget.dataset.id;
      let store = e.currentTarget.dataset.store;
      if (e.touches.length == 1) {
          // 记录移动的距离
          let disX = e.touches[0].clientX - this.data.startX;
          // 大于0则时向右滑，复位
          if (disX >= 0) {
              // 向右滑
              this.setData({
                  isLeft: 0
              });
          } else {
              // 小于则是向左滑
              this.setData({
                  isLeft: 1
              });
          }
      }
  },
  /**
   * 滑动终点
   * @param {*} e 
   */
  touchEnd (e) {
      let id = e.currentTarget.dataset.id;
      let store = e.currentTarget.dataset.store;
      let delw = this.data.delBtnW;
      if (e.touches.length == 1) {
          let endX = e.touches[0].clientX - this.data.startX;
          if (endX < 0) {
              this.setXmove(id, store, - delw);
          } else {
              this.setXmove(id, store, 0);
          }
      }
  },
  /**
   * 滑动事件
   * @param {*} e 
   */
  touchChange (e) {
      let delw = this.data.delBtnW;
      let store = e.currentTarget.dataset.store;
      let id = e.currentTarget.dataset.id;
      if (this.data.isLeft) {
          if (e.detail.source == 'friction') {
              if (e.detail.x < 0) {
                  this.setXmove(id, store, -delw);
              } else {
                  this.setXmove(id, store, 0);
              }
          }
      } else {
          if (e.detail.source == 'friction') {
              this.setXmove(id, store, 0);
          }
      }
  },
  /**
   * 设置起始位置
   * @param {*} id 
   * @param {*} store 
   * @param {*} x 
   */
  setXmove(id, store, x) {
      let that = this;
      if (store) {
          let cartEffectList = this.data.cartEffectList;
          for (let i in cartEffectList) {
              if (cartEffectList[i].store == store) {
                  for (let j in cartEffectList[i].merchandises) {
                      if (cartEffectList[i].merchandises[j].id == id) {
                          cartEffectList[i].merchandises[j].x = x;
                      }
                  }
              }
          }
          that.setData({
              cartEffectList: cartEffectList,
          });
      } else {
          let cartLapseList = this.data.cartLapseList;
          for (let i in cartLapseList) {
              if (cartLapseList[i].id == id) {
                  cartLapseList[i].x = x;
              }
          }
          that.setData({
              cartLapseList: cartLapseList,
          });
      }
  }

})

